const express = require('express');
const router = express.Router();

// const expressJWT = require('express-jwt');
const secretKey = 'yuan';
const jwt = require('jsonwebtoken');
const cors = require('cors')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' });
const session = require('express-session')
// 加载内置模块
const path = require('path');



// 加载自定义模块
const db = require(path.join(__dirname,'../db.js'))

const svgCaptcha = require('svg-captcha');


router.use(cors({
    origin: true, // 意思是设置 Access-Control-Allow-Origin: 发送请求的源
    credentials: true // 表示响应该请求
}))

// 验证码的接口
router.use(session({
    secret: 'safax',
    saveUninitialized: true,
    resave: false
}));





// 注册的接口
router.post('/api/register', (req, res) => {
    // 将提交的验证码删掉
    delete req.body.verify;
    db('insert into user set ?', req.body, (err, result) => {
        // console.log(err)
        if (err || result.affectedRows < 1) {
            res.json({
                status: 1,
                message: '注册失败'
            })
        } else {
            res.json({
                status: 0,
                message: '注册成功'
            })
        }
    })
})


// 登陆的接口
router.post('/api/login', (req, res) => {
    if (req.body.verify.toUpperCase() !== req.session.captcha.toUpperCase()) {
        return res.json({status: 1, message: '验证码错误'});
    }
    let sql = 'select * from user where username=? and password=?';
    db(sql, [req.body.username, req.body.password], (err, result) => {
        if (err) return console.log(err);
        if (result.length > 0) {
            res.json({
                status: 0,
                message: '登陆成功',
                token: 'Bearer ' + jwt.sign({ username: req.body.username }, secretKey, { expiresIn: '24h' })
            })
        } else {
            res.json({
                status: 1,
                message: '登陆失败',
            })
        }
    })
})



router.get('/api/captcha', function (req, res) {
	var captcha = svgCaptcha.create();
	req.session.captcha = captcha.text;
	
	res.type('svg');
	res.status(200).send(captcha.data);
});


// 使用 module.exports 向外共享路由对象
module.exports = router;